package net.bwie.realtime.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.dws.log.bean.MonitorInfo;
import net.bwie.realtime.dws.log.function.CarSpeedingFilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import utils.KafkaUtil;


public class CarSpeedingMonitoring {

    public static void main(String[] args) throws Exception{

        //1.执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2.读取数据源
        DataStream<String> carStream = KafkaUtil.consumerKafka(env, "traffic_monitor_data");
//        carStream.print();

        //3.数据处理
        DataStream<String> resultStream = handle(carStream);
        resultStream.print("result");
        //4.数据输出


        //5.执行
        env.execute("CarSpeedingMonitoring");
    }

    private static DataStream<String> handle(DataStream<String> stream) {

        //a.将字符串转化成MonitorInfo对象
        SingleOutputStreamOperator<MonitorInfo> mapStream = stream.map(new MapFunction<String, MonitorInfo>() {
            @Override
            public MonitorInfo map(String value) throws Exception {
                return JSON.parseObject(value, MonitorInfo.class);
            }
        });

        //b.判断超速的车辆
        SingleOutputStreamOperator<MonitorInfo> filterStream = mapStream.filter(new CarSpeedingFilterFunction());

        //c.将数据转换成json字符串
        SingleOutputStreamOperator<String> resultStream = filterStream.map(
                (MapFunction<MonitorInfo, String>) value -> JSON.toJSONString(value)
        );

        return resultStream;
    }
}
